#include "player.h"
#include <QKeyEvent>
#include <QDebug>
#include<QFile>
#include<QTimer>
#include<QGraphicsItem>

Player::Player(QGraphicsItem *parent)
    : GameObject(parent),
    jumping(false),
    velocity(0),
    gravity(0.3),
    jumpForce(-15),
    groundLevel(300),
    currentLane(1),
    laneWidth(100),
    moveSpeed(10)
 // 调试：打印资源路径是否存在
{
    qDebug() << "Player图像路径有效:" << QFile(":/image/D:/player.jpg").exists();

    // 安全加载图像
    QPixmap pix(":/image/D:/player1.jpg");
    if (pix.isNull()) {
        qDebug() << "使用调试矩形替代";
        QGraphicsRectItem *debugRect = new QGraphicsRectItem(0, 0, 50, 50, this);
        debugRect->setBrush(Qt::red);
    } else {
        setPixmap(pix.scaled(60, 60));
    }

    setFlag(QGraphicsItem::ItemIsFocusable, true);  // 必须启用
    setFocus();  // 立即请求焦点
}
void Player::update()
{
    if(jumping) {
        setPos(x(), y() + velocity);
        velocity += gravity;

        if(y() >= groundLevel - (currentLane * laneWidth)) {
            setPos(x(), groundLevel - (currentLane * laneWidth));
            jumping = false;
            velocity = 0;
        }
    }
}

void Player::keyPressEvent(QKeyEvent *event)
{
    qDebug()<<"Key pressed:"<<event->key()<<"|Jumping state:"<<jumping;
    switch(event->key()) {
    case Qt::Key_Space:
        if(!jumping) {
            jumping = true;
            velocity = jumpForce;
            qDebug()<<"Start jumping!Velocity:"<<velocity;
        }
        break;
    case Qt::Key_Left:
        moveLeft();
        break;
    case Qt::Key_Right:
        moveRight();
        break;
    }
}

void Player::moveLeft()
{
    if(currentLane < 2) {
        currentLane++;
        setPos(x(), groundLevel - (currentLane * laneWidth));
    }
}

void Player::moveRight()
{
    if(currentLane > 0) {
        currentLane--;
        setPos(x(), groundLevel - (currentLane * laneWidth));
    }
}
